package com.dudu.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.dudu.bean.AccountBean;
import com.dudu.bean.AppExtendBean;
import com.dudu.enumeration.AbilityTypeEnum;
import com.dudu.service.IAccountExtendService;
import com.dudu.service.IAppExtendService;
import com.dudu.service.ICheckValidityService;
import com.dudu.service.ILogService;
import com.dudu.service.IOperationPlatformService;
import com.dudu.service.IVoiceCaptchaService;
import com.dudu.service.impl.AccountExtendServiceImpl;
import com.dudu.service.impl.AppExtendServiceImpl;
import com.dudu.service.impl.CheckValidityServiceImpl;
import com.dudu.service.impl.LogService;
import com.dudu.service.impl.OperationPlatformServiceImpl;
import com.dudu.service.impl.VoiceCaptchaServiceImpl;
import com.dudu.utils.DateUtils;
import com.dudu.utils.PhoneUtils;

import net.sf.json.JSONObject;
import core.CoreService;

/**
 * 语音验证码
 * 
 * @author 危东
 * @date 2016年5月17日
 * 
 */
public class OpenAbilityVCAPTCHAController extends CoreService implements IOpenAbilityVCAPTCHAController {

    // ims能力调用
    private IVoiceCaptchaService voiceCaptchaService = new VoiceCaptchaServiceImpl();

    private ILogService logService = new LogService();
    // app扩展信息操作
    private IAppExtendService appExtendService = new AppExtendServiceImpl();
    private IAccountExtendService accountExtendService = new AccountExtendServiceImpl();
    // 验证信息类
    private ICheckValidityService checkValidityService = new CheckValidityServiceImpl();
    // 运营平台相关操作
    private IOperationPlatformService operationPlatformService = new OperationPlatformServiceImpl();

    /**
     * 发起语音验证码
     * 
     * @return
     */
    @Override
    public String sendVoiceCaptcha() {
	log.info("load sendVoiceCaptcha 发起语音验证码");
	long begin = Calendar.getInstance().getTimeInMillis();
	List<String[]> checkParamlist = new ArrayList<String[]>();
	// 接口请求参数
	// app_key应用标识
	String app_key = this.getRequest().getParameter("app_key");
	String[] app_keyStr = { "app_key", app_key, "50", "0", "str" };
	checkParamlist.add(app_keyStr);
	// cust_account账号标识
	String cust_account = this.getRequest().getParameter("cust_account");
	String[] cust_accountStr = { "cust_account", cust_account, "50", "0", "str" };
	checkParamlist.add(cust_accountStr);
	// 发起语音短信的用户ID
	String ext_terminalCode = this.getRequest().getParameter("ext_terminalCode");
	String[] ext_terminalCodeStr = { "ext_terminalCode", ext_terminalCode, "50", "0", "str" };
	checkParamlist.add(ext_terminalCodeStr);
	// 时间戳
	String timestamp = this.getRequest().getParameter("timestamp");
	String[] timestampStr = { "timestamp", timestamp, "20", "0", "str" };
	checkParamlist.add(timestampStr);
	// 认证码
	String sign = this.getRequest().getParameter("sign");
	String[] signStr = { "sign", sign, "50", "0", "str" };
	checkParamlist.add(signStr);
	// 被叫号码：以‘,’分割
	String called = this.getRequest().getParameter("called");
	String[] calledStr = { "called", called, "20", "0", "str" };
	checkParamlist.add(calledStr);
	// 发送语音短信的文字信息
	String content = "";
	try {
	    // 对中文编码进行处理
	    content = URLDecoder.decode(this.getRequest().getParameter("content"), "UTF-8");
	} catch (Exception e1) {
	    e1.printStackTrace();
	}
	String[] contentStr = { "content", content, "10", "0", "str" };
	checkParamlist.add(contentStr);
	// 强制使用平台号码(值为1时，强制使用平台号码发起)
	String usePlatNbr = this.getRequest().getParameter("usePlatNbr");
	String[] usePlatNbrStr = { "usePlatNbr", usePlatNbr, "20", "1", "str" };
	checkParamlist.add(usePlatNbrStr);
	if (StringUtils.isBlank(usePlatNbr) || !"1".equals(usePlatNbr)) { // 不为1时不强制使用平台号
	    usePlatNbr = "";
	}

	JSONObject object = null;
	try {
	    object = this.checkParams(checkParamlist);
	    if (null == object) {
		object = new JSONObject();
		// 判断手机号码是否正确，过滤外国号码等
		if (PhoneUtils.filterIssueNumber(called)) {
		    // 处理重复的电话号码
		    called = PhoneUtils.phoneNumDereplication(called);
		    // 查询应用信息
		    AppExtendBean appExtendBean = appExtendService.queryAppExtendByIdentify(app_key);
		    // 判断app信息是否为空
		    if (appExtendBean != null) {
			// 根据cust_account查询账号信息
			AccountBean accountBean = accountExtendService.queryAccountDetailByCustAccount(cust_account);
			// 判断账号信息是否找到
			if (accountBean != null) {
			    // 验证秘钥信息
			    if (checkValidityService.toolsCheckSign(cust_account, accountBean.getKey_private(), timestamp, sign)) {
				// 获取语音验证码能力类型标识
				String abilityType = AbilityTypeEnum.VCAPTCHA.getKey();
				// 到运营平台验证账号相关信息--判断是否可以通话
				if (operationPlatformService.platformAuthentication(object, appExtendBean, accountBean, abilityType)) {
				    // 发起语音验证码
				    object = voiceCaptchaService.sendVoiceCaptcha(appExtendBean, accountBean, ext_terminalCode, called, content, usePlatNbr);
				} else {
				    object.put("result", "-1");
				    object.put("code", object.getString("code"));
				    object.put("describe", object.getString("describe"));
				}
			    } else {
				object.put("result", "-1");
				object.put("describe", "参数sign错误");
				object.put("code", "0001");
			    }
			} else {
			    object.put("result", "-1");
			    object.put("describe", "计费账号不存在");
			    object.put("code", "0002");
			}
		    } else {
			object.put("result", "-1");
			object.put("describe", "请使用正确的应用标识");
			object.put("code", "0007");
		    }
		} else {
		    object.put("result", "-1");
		    object.put("describe", "号码格式错误");
		    object.put("code", "0004");
		}
	    }
	} catch (Exception e) {
	    log.info("********语音验证码发送失败**********" + e);
	    object = new JSONObject();
	    object.put("result", "-1");
	    object.put("describe", "语音验证码异常");
	    object.put("errorMsg", e.getMessage());
	    object.put("code", "0601");
	}

	// 计算结束时间
	double end = Calendar.getInstance().getTimeInMillis();
	// 计算发起接口道调用完毕所用的时间
	double during = Double.valueOf((end - begin)) / 1000;
	// 拼写写入日志内容
	String request_msg = "ext_terminalCode:" + ext_terminalCode + "|app_key:" + app_key + "|cust_account:" + cust_account + "|called:"
		+ (called.length() > 200 ? called.substring(0, 200) : called) + "|timestamp:" + timestamp + "|sign:" + sign + "|content:" + content + "|usePlatNbr:" + usePlatNbr;
	this.logService.logInterface(during, "sendVoiceCaptchaV4", request_msg.length() > 500 ? request_msg.substring(0, 500) : request_msg,
		object.toString().length() > 200 ? object.toString().substring(0, 200) : object.toString(), object.getString("result").length() > 200 ? object.getString("result")
			.substring(0, 200) : object.getString("result"), DateUtils.getCurrentTime(), this.getRequest().getRemoteAddr(), called);
	object.remove("errorMsg");
	return returnData(object.toString());
    }

}
